package com.beaven.imclient.presenter.chat;

import com.beaven.model.Factory;
import com.beaven.model.data.helper.MessageHelper;
import com.beaven.model.data.message.MessagePresenter;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.api.message.MsgCreateModel;
import com.beaven.model.model.card.MessageCard;
import com.beaven.model.model.db.Message;
import java.util.List;
import rx.Subscriber;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/6/1 9:17
 */

public class ChatUserPresenter extends MessagePresenter implements ChatUserContract.Presenter {

  private ChatUserContract.View view;
  private String receiverId;

  public ChatUserPresenter(ChatUserContract.View view, String receiverId) {
    super(receiverId, false);
    this.receiverId = receiverId;
    this.view = view;
  }

  @Override public void subscribe() {
    loadRepo();
  }

  @Override public void unSubscribe() {
    destroy();
  }

  @Override public void sendMsg(String content) {
    final MsgCreateModel model =
        new MsgCreateModel.Builder().receiver(receiverId, Message.RECEIVER_TYPE_NONE)
            .content(content, Message.TYPE_STR)
            .build();

    MessageHelper.push(model).subscribe(new Subscriber<RspModel<MessageCard>>() {
      @Override public void onCompleted() {

      }

      @Override public void onError(Throwable e) {
        MessageCard card = model.buildCard();
        card.setStatus(Message.STATUS_FAILED);
        Factory.getMessageCenter().dispatch(card);
        Timber.e("消息发送失败--" + e);
      }

      @Override public void onNext(RspModel<MessageCard> messageCardRspModel) {
        if (messageCardRspModel.isSuccess()) {
          MessageCard messageCard = messageCardRspModel.getResult();
          Timber.i("消息成功内容---" + messageCard.getContent());
          Factory.getMessageCenter().dispatch(messageCard);
        } else {
          onError(null);
        }
      }
    });
  }

  @Override public void loadData(List<Message> messages) {
    view.showList(messages);
  }
}
